package team.zero.lemon.common.authz.Interceptor;

import team.zero.lemon.common.authz.annotation.AuthPermission;
import team.zero.lemon.common.exception.AuthException;
import team.zero.lemon.common.exception.CustomException;
import team.zero.lemon.common.exception.PermissionException;
import team.zero.lemon.common.mapper.JsonMapper;
import team.zero.lemon.common.security.session.model.Function;
import team.zero.lemon.common.security.session.model.Session;
import team.zero.lemon.common.security.session.SessionManager;
import team.zero.lemon.common.authz.annotation.AuthPassport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by wangbolin on 15/6/11.
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(getClass());

    public AuthInterceptor() {
        super();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {

            //String requestUri = request.getRequestURI();
            //String contextPath = request.getContextPath();
            //String url = requestUri.substring(contextPath.length());

            AuthPassport authPassport = ((HandlerMethod) handler).getMethodAnnotation(AuthPassport.class);
            //没有声明需要权限,或者声明不验证权限
            if (authPassport == null || authPassport.validate() == false) {
                return true;
            } else {
                //在这里实现自己的权限验证逻辑
                String token = request.getParameter("token");
                if (token == null || token == "") {
                    logger.debug("本次请求无效，没有token");
                    throw new AuthException("无效口令，请联系管理员获取口令再进行访问！");
                }
                Session session = SessionManager.getIstance().get(token);
                if (session != null)//如果验证成功返回true（这里直接写false来模拟验证失败的处理）
                {
                    SessionManager.getIstance().SetCurrentSessionToken(token);
                    AuthPermission authPermission = ((HandlerMethod) handler).getMethodAnnotation(AuthPermission.class);
                    if (authPermission == null) {
                        return true;
                    } else {
                        String permission = authPermission.value();
                        boolean result = false;
                        for (Function function : session.getFunctions()) {
                            String permissions = function.getPermission();
                            if (permissions != null && permissions.contains(permission)) {
                                result = true;
                                break;
                            }
                        }
                        if (result) {
                            return true;
                        } else {
                            logger.debug("本次请求无效，没有访问权限！");
                            throw new PermissionException("无效权限，请联系管理员获取操作权限再进行访问！");
                        }
                    }
                } else//如果验证失败
                {
                    throw new AuthException("您尚未登录系统或者登陆已过有效期，请重新登陆系统再进行访问！");
                }
            }
        } else {
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
    }
}
